var url = require('url')

//改变res 绑定res.send()
function changeRes(res) {
    
    res.send = function (data) {
        res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"})
        res.end(data)
    }
}

//暴露模块
var Server = function () {

    var G = this

    this._get = {}
    this._post = {}

    var app = function (req, res) {

        //给res添加方法
        changeRes(res)

        var pathname = url.parse(req.url).pathname
        if  (!pathname.endsWith('/')) {
            pathname = pathname + '/'
        }

        //获取请求的方式 get post
        var method = req.method.toLowerCase()

        if (pathname != '/favicon.ico/') {
            
            if (G['_'+method][pathname]) {
                
                if (method == 'post') {/*执行post请求*/

                    var postStr = ''

                    req.on('data', function (chunk) {

                        postStr += chunk

                    })
                    
                    req.on('end',function (err,chunk) {

                        req.body = postStr
                        console.log(postStr)

                    })

                    G['_post'][pathname](req,res)

                }else {/*执行get请求*/
                    
                    G['_get'][pathname](req,res)
                    
                }
                
            }else {

                res.end('no-router')
            }
        }
    }
    
    app.get = function (string, callback) {
        if (!string.endsWith('/')) {
            string = string + '/'
        }
        if (!string.startsWith('/')) {
            string = '/' + string
        }
        G._get[string] = callback

    }

    app.post = function (string, callback) {
        if (!string.endsWith('/')) {
            string = string + '/'
        }
        if (!string.startsWith('/')) {
            string = '/' + string
        }
        G._post[string] = callback

    }



    return app

}

module.exports = Server()